package com.example.edwincompose.feature.splash

import android.os.CountDownTimer
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

/**
 * 启动页面VM
 */
class SplashViewModel:ViewModel() {

    private var timer: CountDownTimer?=null
    private val _timeLeft  = MutableStateFlow(0L)
    val timeLeft:StateFlow<Long> = _timeLeft

    /**
     * 是否跳转到主界面
     */
    val navigateToMain = MutableStateFlow(false)

    init {
        delayToNext()
    }

    private fun delayToNext(time:Long=3000) {
        timer = object :CountDownTimer(time,1000){
            /**
             * 每次倒计时执行
             */
            override fun onTick(millisUntilFinished: Long) {
                _timeLeft.value = millisUntilFinished/1000+1
            }

            override fun onFinish() {
                toNext()
            }

        }.start()
    }

    fun toNext(){
        //这里我们不能直接写跳转的代码，因为这是页面层做的事情，所以我们还是通过一个变量来通知
        navigateToMain.value = true
    }

    fun returnSplash(){
        timer?.cancel()
        toNext()
    }

}